package net.wxxr.http.util;

import android.util.Log;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import com.ykdl.member.base.GlobalContext;
import com.ykdl.member.kid.util.AccessTokenKeeper;
import com.ykdl.member.kid.util.MD5;

/**
 * Created by yuanwenfei on 2014/6/5.
 * 生成认证签名
 */
public class Sig {
	AccessTokenKeeper keeper = new AccessTokenKeeper(GlobalContext.mContext);
	String TAG = "Sig";
	
    public String getSig(Map<String, String> map2) {
        StringBuilder  sb = new StringBuilder();
        List<String>  list = new LinkedList<String>();
        ConcurrentHashMap<String, String> map = null;
        if(map2 != null && !map2.isEmpty()){
        	map = new ConcurrentHashMap<String, String>();
        	Set<String>   keys = map2.keySet();
        	String value;
        	for(String key : keys){
//        		value = (String) multiMap.getFirst(key);
        		value = String.valueOf(map2.get(key));
        		map.put(key, value);
        	}
        }
        
        if(null != map){
            Iterator iter = map.entrySet().iterator();
            Set<String> keySet = map.keySet();
            for(String key: keySet){
            	list.add(key);
            }
            Collections.sort(list);
    
            
        }

        StringBuffer readyForHash = new StringBuffer();

        int k = 0;
        for(int i=0; i < list.size();i++){
            String key = list.get(i);
            String value = null;
            try {
                value = new String(map.get(key).getBytes(), "utf-8").toString();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            readyForHash.append( key + "=" + value);
            if(k < (list.size() -1)){
                readyForHash.append("&");
            }
            k++;
        }

//        if(null != access_token && access_token.trim().length() > 0){
//            readyForHash.append("&");
//            readyForHash.append(access_token);
//        }
        
        if(null != keeper.getmAccessToken()&&keeper.getmAccessToken().trim().length()>0){
            readyForHash.append("&");
            readyForHash.append(keeper.getmAccessToken());
        }

        //UUID
        readyForHash.append("&9f935e82-c127-11e3-bf6b-10ddb1c4d76b");
        Log.d(TAG, "readyForHash:"+ readyForHash.toString());
        String md5 = MD5.Md5(readyForHash.toString());
        Log.d(TAG, "sig:"+ md5);
        sb.append(md5);

        
        return sb.toString();
    }


}
